<template>
  <div>
    <div class="node" v-has="{action: 'company:group:list', effect: 'move'}">
      <div class="search_box topSelect">
        <SearchInput
          placeholder="集团名称"
          label="集团名称"
          style="margin-right:20px"
          :value="searchs.name"
          :onChange="(val) => changeSearch('name',val)"
          :onBlur="getPile"
        />
        <div class="selectBox">
          <label>状态：</label>
          <el-select
            v-model="searchs.state"
            clearable
            @change="pageChange(1)"
            placeholder="请选择状态"
          >
            <el-option label="未启用" :value="0"></el-option>
            <el-option label="启用" :value="1"></el-option>
          </el-select>
        </div>
        <div class="searchBox1" style="margin-left: 20px">
          <el-button size="small" plain icon="el-icon-search" @click="getPile">查询</el-button>        
        </div>
      </div>
      <Panel title="集团大客户" :intro='intro' useBack>
        <div slot='ext' class="examine">
          <el-button v-has="{action: 'company:group:add', effect: 'move'}" class="button-offt" type="success" icon="el-icon-plus" @click="()=>edit()">新增</el-button>
      </div>
      <TableEncapsulation
        slot="body"
        :tableConfig="tableConfig"
        :tableData="tableData"
      >
      <template slot="operation" slot-scope="operation">
            <el-button size="mini" icon="el-icon-edit"
            v-has="{action: 'company:group:update', effect: 'move'}"
              @click="()=>edit(operation.row)"
            >编辑</el-button>
            <el-button size="mini" icon="el-icon-money"   type="success" plain
              v-has="{action: 'charge:group:charge', effect: 'move'}"
              @click="()=>charge(operation.row)"
            >余额充值</el-button>
            <el-button size="mini" icon="el-icon-document"
              @click="()=>balance(operation.row.id)"
            >余额日志</el-button>
              <el-button size="mini" icon="el-icon-operation"
              v-has="{action: 'group:user:time:list', effect: 'move'}"
              @click="()=>timeSet(operation.row)"
            >使用时间段</el-button>
            <el-button  size="mini" icon="el-icon-document"
              @click="()=>showSite(operation.row.id)"
            >映射站点</el-button>
            <el-button  size="mini" icon="el-icon-tools"
              @click="()=>showRate(operation.row)"
            >费率配置</el-button>
            <el-button size="mini" icon="el-icon-user"
              @click="()=>showUser(operation.row.id)"
            >集团用户</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete"
              v-has="{action: 'company:group:delete', effect: 'move'}"
              @click="()=>remove(operation.row.id)"
            >删除</el-button>
          </template>
          <TablePager
            slot="pager"
            v-if="pager.use"
            :size="pager.size"
            :pageChange="pageChange"
            :show-total="pager.showTotal"
            :total="pager.total"
            :current="pager.current"
          >
            <span class="demonstration">GO></span>
          </TablePager>
      </TableEncapsulation>
      </Panel>
      <!-- 添加编辑 start-->
      <ModalPanel 
        :visible='add'
        title="添加/编辑"
        :onCancel="onCancelAdd"
        class="bannerDialog"
        :onOk="onSubmit">
        <div>
          <ModifyForm
            :hiddenBtn='true'
            :editColumn='editColumnAdd'
            :updateData="updateDataAdd"
            labelWidth='100px'
            ref="configModal"
            class="ModifyForm"
            :temporaryData='modalDataAdd'>
          </ModifyForm>
        </div>
      </ModalPanel>
      <!-- 添加编辑end -->
      <!-- 时间段 start-->
      <ModalPanel 
        :visible='setTime'
        title=""
        width="70%"
        :onCancel="onCancelTime"
        :showFooter="false"
        class="bannerDialog"
        :onOk="onSubmit">
        <Panel title="使用时间段">
        <div slot="body">
          <el-form :inline="true" class="demo-form-inline" id="formData">
          <div class="box">
            <el-button  type="primary" @click="addIds()" style="margin-left:10px;margin-bottom:20px">加一行</el-button>
            
            <div class="block" v-for="(item, index) of formData.times" :key="index">
            <el-slider
              width="500px"
              v-model="item.value"
              :format-tooltip="formatTooltip"
              range
              show-stops
              :step="1"
              :max="1439"
              :marks="marks">
            </el-slider>
            <el-button  type="primary"  @click="deleteIds(index)" style="margin-left:10px">删除</el-button>
          </div>
          <el-button style="margin-left:40%" type="primary" @click="submit" >保存</el-button>
          </div>
          </el-form>
        </div>
      </Panel>
      </ModalPanel>
      <!-- 时间段 end -->
    <ModalPanel 
        :visible='visible'
        title="充值"
        :onCancel="onCancel"
        class="bannerDialog"
        :onOk="onSubmit1">
        <div>
          <ModifyForm
            :hiddenBtn='true'
            :editColumn='editColumn'
            :updateData="updateData"
            labelWidth='100px'
            ref="charge"
            class="ModifyForm"
            :temporaryData='modalData'>
          </ModifyForm>
        </div>
      </ModalPanel>
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'company:group:list', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import { objectFilter } from "@/tools/array";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
export default {
  name: "companyCustomer",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput,
    ModifyForm,
    ModalPanel,
    
  },
  data() {
    return {
      intro: {
        title: '集团大客户-介绍说明',
        content: `<ul><li>集团大客户可以定制专属充电费率；并且根据设置，用户可以从集团余额中直接扣除充电费用（详见集团用户）</li><li>集团充值余额采用预支付方式，可设置最高可欠费金额。</li><li>创建集团后，必须配置 ‘可使用时间段’、‘映射站点’、‘费率配置’，集团用户才可正常充电。</li></ul><p><br></`
      },
      tableData: [],
      searchs:{
        name:'',
        state:''
      },
      visible: false,
      modalData: {},
      pager: {
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      name: '',
      operation: true,

      //时间段
      setTime: false,
      modalDataTime:{},
      value: [30, 60],
        marks: {
        0: "00:00",
        180: {
          label: "03:00",
        },
        360: {
          label: "06:00",
        },
        540: {
          label: "09:00",
        },
        720: {
          label: "12:00",
        },
        900: {
          label: "15:00",
        },
        1080: {
          label: "18:00",
        },
        1260: {
          label: "21:00",
        },
        1439: {
          style: {
            width: "36px",
          },
          label: "23:59"
        }
      },
      formData: {
        times: [
          {value: [30, 60]}
        ],
      },
      //end
      editColumn: [
        {
          name: "充值金额",
          prop: "price",
          type: "number",
          required: true,
          width: 24
        },
        {
          name: "备注",
          prop: "detail",
          type: "text",
          required: false,
          width: 24
        },
        
      ],
      //添加编辑
      add:false,
      modalDataAdd:{},
      editColumnAdd: [
        {
          name: "集团名称",
          prop: "name",
          type: "text",
          width:24,
          required: true
        },
       
         {
          name: "状态",
          prop: "state",
          type: "radio",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': 1,'name': "启用"},{'id':0, 'name':"未启用"}],
          width:24,
          required: true
        },
        {
          name: "账号最高欠费金额",
          width: 24,
          prop: "maxArrears",
          type: "number",
          required: true
        },
       
        {
          name: "备注",
          width: 24,
          prop: "mark",
          type: "text",
          required: false
        },
      ],
      //添加编辑end
    };
  },
  created() {
    this.getPile();
  },
  computed: {
    tableConfig () {
      return {
        selection: false,
        columnConfig: [
          {
            label: "集团名称",
            type: "text",
            prop: "name",
            align: "center"
          },
          {
            label: "余额",
            type: "text",
            prop: "balance",
            align: "center"
          },
          {
            label: "账号最高欠费金额",
            type: "text",
            prop: "maxArrears",
            align: "center"
          },
          {
            label: "状态",
            type: "other",
            prop: "state",
            align: "center",
            fnc: val => val == 1 ? "启用":"未启用",
            class: val => val == 1 ? 'agree': 'cancel',
          },
          {
            label: "备注",
            type: "text",
            prop: "mark",
            align: "center"
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:440
          }
        ].filter(Boolean)
        }
    }
  },
  methods: {
    async getPile() {
      let page = this.pager.current
      let name = this.searchs.name
      let state = this.searchs.state
      let search = objectFilter({ name, state, page })
      const res = await request({
        url: "/company/group/list",
        method: "POST",
        data: search
      });
      this.tableData = res.page.list
      this.pager.total = res.page.totalCount
      this.pager.current = res.page.currPage
    },
    pageChange(val) {
      this.pager.current = val;
      this.getPile();
    },
    changeSearch(key, val) {
      this.searchs[key] = val;
      this.pager.current = 1;
    },
    charge(rowData){
      let data = {
        price:0,uid:rowData.id,detail:''
      }
      this.modalData = data
      this.visible = true
    },
    async updateData(values){
      let url, msg
      url = '/charge/group/charge'
      msg = '充值成功'
    let res = await request({
      url: url,
      method: 'POST',
      data: values
    })
    if (res.code !==0) return
     this.$message.success(msg)
      this.visible = false
      this.getPile()
    },
    onCancel(){
      this.visible = false
    },
    async onSubmit(){
      this.$refs['configModal'].onSubmit()
    },

    //添加编辑start
    edit(rowData){
      if(rowData){
        this.modalDataAdd = {...rowData}
      }else{
        this.modalDataAdd ={}
      }
      this.add = true
    },
    async onSubmit1(){
      this.$refs['charge'].onSubmit()
    },
    onCancelAdd(){
      this.add = false
    },
    async updateDataAdd(values){
     const {id, name, balance, contactsPhone, mark, maxArrears, state } = values
     let url = id ? "/company/group/update": "/company/group/add"
     let msg = id ? "编辑成功" : "添加成功"
     let res = await request({
       url: url,
       method: "POST",
       data: {id, name, balance, contactsPhone, mark, maxArrears, state }
     })
     if(res.code !==0) return
      this.$message.success(msg)
      this.add = false
      this.getPile();
    },
    //添加编辑end

    //时间段
    onCancelTime(){
      this.setTime = false
    },
    formatTooltip(val) {
        let hour = 0;
        let min = 0;
        hour = parseInt(val / 60);
        if (hour < 10) {
          hour = "0" + hour.toString();
        } else {
          hour = hour.toString();
        }
        min = val - hour * 60;
        if (min < 10) {
          min = "0" + min.toString();
        } else {
          min = min.toString();
        }
        let time = hour + ":" + min;
        return time;
      },
      addIds(){
        this.formData.times.push({})
      },
      deleteIds(index) {
          this.formData.times.splice(index, 1)
      },
      async submit() {
         let this_ = this
          let data = this.formData.times
          if (!data) return this.$message.error('至少包含一条数据')
          let arr = []
          let start ,end
          let isWan = true
          data.map((item, index) => {
            // if(!item.value[0] || !item.value[1]){
            //   isWan = false
            // } 
            start = this_.formatTooltip(item.value[0])
            end = this_.formatTooltip(item.value[1])
            arr.push({'beginTime': start+':00', 'endTime': end+':59'})
            return item
          })
          // if(!isWan){
          //   return this.$message.error('请完善时间段')
          // }
          function compare(property,desc) {
                return function (a, b) {
                    var value1 = a[property];
                    var value2 = b[property];
                    if(desc==true){
                        // 升序排列
                        return value1 - value2;
                    }else{
                        // 降序排列
                        return value2 - value1;
                    }
                }
            }
          arr.sort(compare('beginTime',true))
          // if(ret == false) return this.$message.error(msg)
          // return
          let res = await request({
          url: '/group/use/time/update',
          method: 'POST',
          data: {id:this.modalDataTime.id, list:arr}
          })
          if (res.code !==0) return
          this.$message.success('提交成功')
          this.setTime = false


    },
    async getRate(id) {
      const { list } = await request({
        url: "/group/use/time/list",
        method: "POST",
        data: id,
      });
      let arr = []
      list.map( item => {
        var begin = item.beginTime.split(":")
        var num1 = 60 * parseInt(begin[0]) + parseInt(begin[1])
        var end = item.endTime.split(":")
        var num2 = 60 * parseInt(end[0]) + parseInt(end[1])
        arr.push({value: [num1, num2]})
        return  item
      })

      this.formData.times = arr
    },
    timeSet(rowData){
      if(rowData){
        this.modalDataTime = {...rowData}
      }else{
        this.modalDataTime ={}
      }
      this.getRate(rowData.id)
      this.setTime = true
    },
    // 时间段
    
    showSite(id){
      this.$router.push({ path: "/company/map/info",query:{id:id} })
    },
    showRate(row){
      this.$router.push({ path: "/company/rate/list",query:{id:row.id, name: row.name} })
    },
    showUser(id){
      this.$router.push({ path: "/company/user/list",query:{id:id} })
    },
    balance(id){
      this.$router.push({ path: "/company/group/balance",query:{id:id} })
    },
    remove(id){
       this.$confirm('确认删除吗', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
       let res =  await request({
          url: '/company/group/delete',
          method:"POST",
          dataType:'json',
          data: [id]
        })
        if(res.code !==0) return
        this.$message.success('删除成功')
        if(this.tableData.length===1 && this.pager.current>1)
          this.$set(this.pager,'current', this.pager.current-1)
        this.getPile()
      })
    },
  }
}
</script>
<style lang='scss' >
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}

.topSelect {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.block {
  padding: 27px 10px;
  width: 660px;
  display: flex;
  justify-content: space-around;
}
.block div {
  // width: 568px;
}
.el-slider__runway {
  width: 500px !important;
}
.box {
  background: #f3f3f3;
  padding: 20px;
}
.band{
  margin: 2px 8px;
}
</style>